package wsepForum.ui.swing.innerPanels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Vector;
import java.util.concurrent.ExecutionException;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;

import wsepForum.common.elements.SearchResult;
import wsepForum.domain.exceptions.SystemFailureException;
import wsepForum.network.client.GUIController;
import wsepForum.network.common.GUIAnswer;
import wsepForum.network.common.GUIAnswer.AnswerType;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.persistance.exceptions.WrongUserNameException;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.workers.ForumWorker;

public class SearchPanel extends AInnerPanel {

	private static final long serialVersionUID = 2549294925792983768L;

	JTextField textSrchByContent;

	Vector<String> usernameList;

	public SearchPanel(AOuterPanel oPanel, final Vector<String> userList) {
		super(oPanel);

		this.usernameList = userList;
		setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
		setLayout(null);
		setBackground(new Color(230, 230, 250));
		setBounds(20, 93, 716, 364);

		initPanel();
	}

	private void initPanel(){

		JLabel lblLogin = new JLabel("Search");
		lblLogin.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		lblLogin.setHorizontalAlignment(SwingConstants.CENTER);
		lblLogin.setBounds(311, 11, 94, 40);
		add(lblLogin);

		final JComboBox fromDayComboBox = new JComboBox();
		fromDayComboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
		fromDayComboBox.setBounds(319, 199, 48, 20);
		add(fromDayComboBox);


		final JComboBox fromMonthComboBox = new JComboBox();
		fromMonthComboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}));
		fromMonthComboBox.setBounds(377, 199, 48, 20);
		add(fromMonthComboBox);


		final JComboBox fromYearComboBox = new JComboBox();
		fromYearComboBox.setModel(new DefaultComboBoxModel(new String[] {"2009", "2010", "2011", "2012"}));
		fromYearComboBox.setBounds(435, 199, 58, 20);
		add(fromYearComboBox);


		final JComboBox toDayComboBox = new JComboBox();
		toDayComboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
		toDayComboBox.setBounds(319, 232, 48, 20);
		add(toDayComboBox);


		final JComboBox toMonthComboBox = new JComboBox();
		toMonthComboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"}));
		toMonthComboBox.setBounds(377, 233, 48, 20);
		add(toMonthComboBox);

		final JComboBox toYearComboBox = new JComboBox();
		toYearComboBox.setModel(new DefaultComboBoxModel(new String[] {"2009", "2010", "2011", "2012"}));
		toYearComboBox.setBounds(435, 233, 58, 20);
		add(toYearComboBox);

		JLabel lblSearchByDate = new JLabel("Search By Date:");
		lblSearchByDate.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblSearchByDate.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearchByDate.setBounds(149, 195, 102, 26);
		add(lblSearchByDate);

		JLabel lblSearchByAuthor = new JLabel("Search By Author:");
		lblSearchByAuthor.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearchByAuthor.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblSearchByAuthor.setBounds(135, 126, 116, 26);
		add(lblSearchByAuthor);

		JLabel lblFrom = new JLabel("From:");
		lblFrom.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFrom.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblFrom.setBounds(271, 195, 39, 26);
		add(lblFrom);

		JLabel lblTo = new JLabel("to:");
		lblTo.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTo.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblTo.setBounds(271, 229, 39, 26);
		add(lblTo);

		JButton btnDateSearch = new JButton("Search");
		btnDateSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				SearchForumWorker worker = new SearchForumWorker(outerPanel.getConnection()){
					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
							Calendar fromDate = new GregorianCalendar(Integer.valueOf((String)fromYearComboBox.getSelectedItem()), Integer.valueOf((String)fromMonthComboBox.getSelectedItem())-1, Integer.valueOf((String)fromDayComboBox.getSelectedItem()));
							Calendar toDate = new GregorianCalendar(Integer.valueOf((String)toYearComboBox.getSelectedItem()), Integer.valueOf((String)toMonthComboBox.getSelectedItem())-1, Integer.valueOf((String)toDayComboBox.getSelectedItem()));
							GUIAnswer ans = request(RequestType.SEARCH_BY_DATES, new Object[] {fromDate.getTime(),toDate.getTime()}) ;
							outerPanel.setNumOfConnected(ans.getNumOfConnected());
							AInnerPanel returnedPanel = SearchPanel.this;
							if(ans.getAnswerType().equals(AnswerType.ANSWER)){
								returnedPanel = new SearchResultPanel((Vector<SearchResult>) ans.getArguments()[0],SearchPanel.this, outerPanel);
							}
							else {
								returnedPanel = handleSearchExceptions((Exception) ans.getArguments()[0]);
							}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleSearchExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleSearchExceptions(e));
						}
					}
				};
				worker.execute();
			}
		});
		btnDateSearch.setBounds(503, 198, 75, 23);
		add(btnDateSearch);

		final JComboBox authorListField = new JComboBox(this.usernameList);
		authorListField.setBounds(271, 130, 222, 20);
		add(authorListField);

		JButton btnAuthorSearch = new JButton("Search");
		btnAuthorSearch.setBounds(503, 129, 75, 23);
		btnAuthorSearch.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				SearchForumWorker worker = new SearchForumWorker(outerPanel.getConnection()){
					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
							GUIAnswer ans = request(RequestType.SEARCH_BY_AUTHOR, new Object[] {usernameList.get(authorListField.getSelectedIndex())}) ;
							outerPanel.setNumOfConnected(ans.getNumOfConnected());
							AInnerPanel returnedPanel = SearchPanel.this;
							if(ans.getAnswerType().equals(AnswerType.ANSWER)){
								returnedPanel = new SearchResultPanel((Vector<SearchResult>) ans.getArguments()[0],SearchPanel.this, outerPanel);
							}
							else {
								returnedPanel = handleSearchExceptions((Exception) ans.getArguments()[0]);
							}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleSearchExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleSearchExceptions(e));
						}
					}
				};
				worker.execute();
			}
		});
		add(btnAuthorSearch);


		JLabel lblSearchByText = new JLabel("Search By Text:");
		lblSearchByText.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearchByText.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblSearchByText.setBounds(135, 62, 116, 26);
		add(lblSearchByText);

		textSrchByContent = new JTextField();
		textSrchByContent.setColumns(10);
		textSrchByContent.setBounds(271, 66, 222, 20);
		add(textSrchByContent);

		JButton btnTextSearch = new JButton("Search");
		btnTextSearch.setBounds(503, 65, 75, 23);
		btnTextSearch.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				SearchForumWorker worker = new SearchForumWorker(outerPanel.getConnection()){
					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
							GUIAnswer ans = request(RequestType.SEARCH_BY_CONTENT, new Object[] {textSrchByContent.getText()}) ;
							outerPanel.setNumOfConnected(ans.getNumOfConnected());
							AInnerPanel returnedPanel = SearchPanel.this;
							if(ans.getAnswerType().equals(AnswerType.ANSWER)){
								returnedPanel = new SearchResultPanel((Vector<SearchResult>) ans.getArguments()[0],SearchPanel.this, outerPanel);
							}
							else {
								returnedPanel = handleSearchExceptions((Exception) ans.getArguments()[0]);
							}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleSearchExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleSearchExceptions(e));
						}
					}
				};
				worker.execute();
			}
		});

		add(btnTextSearch);
	}

	private abstract class SearchForumWorker extends ForumWorker<AInnerPanel>{

		protected SearchForumWorker(GUIController controller) {
			super(controller);
		}

		protected AInnerPanel handleSearchExceptions(Exception thrown){
			try {
				throw thrown;
			} catch (WrongUserNameException e) {
				JOptionPane.showMessageDialog(null, "user " + e.getWrongUsername() + " is no longer exist. please select diferent user", "Login Fail",JOptionPane.ERROR_MESSAGE);
				usernameList.remove(e.getWrongUsername());
				return new SearchPanel(outerPanel, usernameList);
			} catch (SystemFailureException e) {
				JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
				return requestHomePanel(outerPanel);
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
				return requestHomePanel(outerPanel);
			}
		}
	}
}
